package com.zt.questionnaire.common.typehandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class EntityJsonTypeHandler extends BaseTypeHandler<JSONObject> {


//	private String toJson(JSONObject json) {
//		try {
//			return json.toJSONString();
//		} catch (Exception e) {
//			throw new RuntimeException(e);
//		}
//	}

	private JSONObject toObject(String content) {
		if (content != null && !content.isEmpty()) {
			try {
				return JSONObject.parseObject(content);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		} else {
			return null;
		}
	}

	@Override
	public JSONObject getNullableResult(ResultSet rs, String arg1) throws SQLException {
		return this.toObject(rs.getString(arg1));
	}

	@Override
	public JSONObject getNullableResult(ResultSet rs, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return this.toObject(rs.getString(arg1));
	}

	@Override
	public JSONObject getNullableResult(CallableStatement cs, int arg1) throws SQLException {
		// TODO Auto-generated method stub
		return this.toObject(cs.getString(arg1));
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int arg1, JSONObject arg2, JdbcType arg3)
			throws SQLException {
		ps.setString(arg1, arg2.toJSONString());
	}
}
